package com.heima.user.service.impl;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AppLoginDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.AppLoginService;
import com.heima.user.util.SMSsend;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author mrchen
 * @date 2022/5/2 9:28
 */
@Service
public class AppLoginServiceImpl implements AppLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult login(AppLoginDTO dto) {
        String phone = dto.getPhone();
        String code = dto.getCode();
        if (StringUtils.isNotBlank(phone) && StringUtils.isNotBlank(code)) {
            ApUser apUser = apUserMapper.selectOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, phone));
            if (Objects.isNull(apUser)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "对应的用户信息不存在");
            }
            //锁定账户
            if (redisTemplate.hasKey(phone + "flase")) {
                apUser.setStatus(true);
                apUserMapper.updateById(apUser);
                CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
            }
            String userId = apUser.getId().toString();
            if (redisTemplate.hasKey(userId + "Flase")) {
                redisTemplate.opsForValue().set(phone + "flase", "1");
                CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR, "验证码错误次数过多,请1分钟后重试");
            }
            //TODO 获取redis中的code
            if(redisTemplate.hasKey(phone)) {
                String tCode = redisTemplate.opsForValue().get(phone);
                if (!code.equals(tCode)) {
//                String s = redisTemplate.opsForValue().get(userId);
//                int count = Integer.parseInt(s);
                    if (!redisTemplate.hasKey(userId)) {
                        redisTemplate.opsForValue().set(userId, "1", 1, TimeUnit.HOURS);
                    } else {
                        redisTemplate.boundValueOps(userId).increment(1);
//                    Long expire = redisTemplate.getExpire(userId);
//                    redisTemplate.opsForValue().set(userId, String.valueOf((count + 1)),expire,TimeUnit.HOURS);
                    }
                    String s = redisTemplate.opsForValue().get(userId);
                    if (Integer.parseInt(s) >= 3) {
                        redisTemplate.opsForValue().set(userId + "Flase", "1", 1, TimeUnit.MINUTES);
                    }
                    CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR, "验证码错误");
                }
                //    1.3 颁发token 并返回  （user    token  ）
                String token = AppJwtUtil.getToken(Long.valueOf(apUser.getId()));
                Map result = new HashMap<>();
                result.put("token", token);
                apUser.setSalt("");
                apUser.setPassword("");
                result.put("user", apUser);
                return ResponseResult.okResult(result);
            }else{
                return ResponseResult.okResult("验证码已失效....");
            }
        } else {
            if (dto.getEquipmentId() == null) {
                //    2.1  判断设备id是否存在
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            //    2.2  直接颁发token  userId存储 0
            String token = AppJwtUtil.getToken(0L);
            Map result = new HashMap<>();
            result.put("token", token);
            return ResponseResult.okResult(result);
        }

    }

    @Override
    public ResponseResult sendCode(String phone) throws ClientException {
        if (phone == null || phone.matches("(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9]){8}")) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (redisTemplate.opsForValue().get(phone) == null) {
            long codeL = System.nanoTime();
            String codeStr = Long.toString(codeL);
            String code = codeStr.substring(codeStr.length() - 8, codeStr.length() - 2);
            redisTemplate.opsForValue().set(phone, code, 1, TimeUnit.MINUTES);
            SendSmsResponse sendSms = SMSsend.sendSms(phone, code);

            if (sendSms.getCode().equals("OK")) {
                return ResponseResult.okResult("短信发送成功....");
            } else {
                return ResponseResult.okResult("短信发送失败....");
            }
        }
        return ResponseResult.okResult("验证码未失效....");

    }

}
